<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Views\Lib;

use Sun\Sun;
use Sun\Html;
use Sun\Utils;
use App\Models;

class Dict extends \Sun\View {

    public function __construct() {
        parent::__construct(null, "Select");
    }

    public function RecPageScene() {
        $edit = new Models\Edition();
        $cond = !empty($this->data['rec'])
            ? "lower(value) LIKE lower(".$edit->db->quote($this->data['rec']."%").")"
            : "true";

        $num_rows = Sun::conf("iface/dict_rows");
        $num_pages = ceil($edit->GetNumDictRecs($this->data['field_id'], $cond) / $num_rows);

        $p = $this->data['Page'];
        $offset = $num_rows * ($p - 1);

        $res = $edit->GetDictRecs($this->data['field_id'], $cond, $offset, $num_rows);

        $table = new Html\QueryTable($res, array("Значение"), false);
        $table->SetAttribute('class', $table->Attribute('class'). ' Dictionary');
        $table->SetAttribute('id', "RecTable");

        ////////////////// javascript //////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Dict/Dict.js");
        $script = new Html\Script($src);
        ////////////////////////////////////////////////////

        $div = new Html\Div();
        $div->add($table);
        $div->Add($script);

        $query_res = "{ content: {$div->ToJSON()}, num_pages: {$num_pages} }";

        echo $query_res;
    }

    public function RecSwitch() {
        $page_switch = new Html\PageSwitch("DictRec", 9);
        return $page_switch;
    }

    public function FieldName() {
        $edit = new Models\Edition();
        $field = $edit->GetFieldData($this->data['field_id']);
        return $field['name'];
    }
}
